iT邦幫忙

2023 iThome 鐵人賽

DAY 19
0
自我挑戰組

30天leetcode學習旅程系列 第 19

項次 19 - Breadth-First Search

  • 分享至 

  • xImage
  •  

題目:199. Binary Tree Right Side View

連結:https://leetcode.com/problems/binary-tree-right-side-view/description/

  • 等級:Medium
class Solution {
    private int maxlevel = 0;
    public void right(TreeNode root,int level,List<Integer> save)
    {
        if (root == null)
            return;
        if (maxlevel < level)
        {
            save.add(root.val);
            maxlevel = level;
        }
        right(root.right,level+1,save);
        right(root.left,level+1,save);
    }
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> save = new ArrayList<Integer>();
        right(root,1,save);
        return save;
    }
}
  • Time complexity: O(n)
  • Space complexity: O(n)

題目:116. Populating Next Right Pointers in Each Node

連結:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

  • 等級:Medium
class Solution {
    public Node connect(Node root) {
        Node head = root;
        for(; root != null; root = root.left) 
            for(Node cur = root; cur != null; cur = cur.next) 
                if(cur.left != null) {
                    cur.left.next = cur.right;
                    if(cur.next != null) cur.right.next = cur.next.left;
                } else break;
        
        return head;
    }
}
  • Time complexity: O(n)
  • Space complexity: O(1)

上一篇
Day 18 - Depth-First Search
下一篇
項次 20 - Breadth-First Search
系列文
30天leetcode學習旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言